package com.vic.filedb.mongo.service.impl;

import com.vic.filedb.mongo.common.exception.FileServerException;
import com.vic.filedb.mongo.entity.File;
import com.vic.filedb.mongo.repository.FileRepository;
import com.vic.filedb.mongo.service.FileService;
import lombok.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Resource
    private FileRepository fileRepository;

    private String serverhost="http://localhost:8080";

    @Override
    public String upload(MultipartFile file) throws FileServerException {
        if (!file.isEmpty()) {
            try {
                //源文件名
                String fileName = file.getOriginalFilename();
                //源文件后缀
                String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
                //数据库文件Id,且以id为新的文件名
                String fileId = UUID.randomUUID() + "";

                if (file.getSize() > 1000 * 1024) {
                    throw new FileServerException("上传失败,图片大于1MB");
                }
                if (!(fileSuffix.equals(".jpg") || fileSuffix.equals(".jpeg") || fileSuffix.equals(".png"))) {
                    throw new FileServerException("上传失败，不支持该图片格式");
                }
                File monFile = new File();
                monFile.setName(fileId);
                monFile.setSize(file.getSize());
                monFile.setContentType(file.getContentType());
                monFile.setContent(file.getBytes());
                File newImage = fileRepository.save(monFile);
                return serverhost + "/file/" + newImage.get_id();
            } catch (Exception e) {
                throw new FileServerException("上传失败，" + e.getMessage());
            }
        } else {
            throw new FileServerException("文件不存在");
        }
    }

    @Override
    public File getFileById(String fileId) {
        return fileRepository.findById(fileId).get();
    }
}
